function originTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "自行注册";
    else if (value == 1)
        return "海报连接";
    else if (value == 2)
        return "激活码";
    else return ""
}

function userTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "试用用户";
    else if (value == 1)
        return "单店管理员";
    else if (value == 2)
        return "总店管理员";
    else if (value == 3)
        return "代理用户";
    else if (value == 4)
        return "运营人员";
    else if (value == 5)
        return "测试人员";
    else if (value == 9)
        return "超级管理员";
    else return ""
}

function apptypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "微信公众号";
    else if (value == 2)
        return "微信小程序";
    else if (value == 3)
        return "微信商城";
    else if (value == 4)
        return "微信app";
    else if (value == 5)
        return "支付宝小程序";
    else if (value == 6)
        return "百度小程序";
    else return ""
}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/user/list'});
        },
        dataType: "json"
    });
}

function setadminphone(id) {
    swal({
        title: "设置用户手机号",
        text: "",
        type: "info",
        input: "text",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        animation: "slide-from-top",
        inputPlaceholder: "输入该用户手机号"
    }).then(function (res) {
        var re = /^[1-9]+[0-9]*]*$/;
        // if(!re.test(inputValue)){
        if (res.length == 0) {
            swal("请输入管理员手机号");
            return;
        }
        if(!(/^1[3-9][0-9]\d{8}$/.test(res))){
            swal("请输入正确的手机号");
            return false;
        }

        console.log("======res=" + res)
        $.ajax({
            type: 'POST',
            url: "setadminphone",
            data: {
                id: id,
                phone: res,
            },
            success: function (e) {
                if (e.code == 0) {
                    swal({title: "操作成功", text: e.info, type: "success"})
                    tbfresh()
                } else {
                    swal({title: "设置用户手机号失败", text: e.msg||"操作失败", type: "error"})
                }
            },
            dataType: "json"
        });
    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function setadmin(id, name, phone) {
    console.log("======id="+id)
    console.log("======phone="+phone)

    $('#hidid').val(id)
    console.log("=======phone=" + phone)
    // if(phone.length==0){
    //     swal({title: "该用户未绑定手机号", text: "", type: "success"})
    //     return;
    // }
    // if (typeof phone == undefined||typeof phone == 'undefined') {
    console.log("======ceshi")
    // swal({
    //     title: "请输入商家用户手机号",
    //     text: "确认输入",
    //     type: "input",
    //     input: 'info',
    //     showCancelButton: true,
    //     closeOnConfirm: false,
    //     animation: "slide-from-top",
    //     inputPlaceholder: "请输入商家用户手机号"
    // }, function (phone) {
    //     if (!phone || phone.length != 11) {
    //         swal({title: "输入的手机号不正确", text: "", type: "warning"})
    //         return;
    //     }
    //     $("#hidphone").val(phone)
    // });

    $.ajax({
        type: 'POST',
        url: "setMuserAdmin",
        data: {
            id: $("#hidid").val(),
            mpid: $("#qstatus").val(),
            phone: phone
        },
        success: function (e) {
            console.log('======ajax return')
            console.log(e)
            if (e.code != 0) {
                swal({title: "该用户未绑定手机号", text: e.msg, type: "warning"})
            } else {

                $('#mytable').bootstrapTable('refresh', {url: '/admin/user/list'});
            }
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/user/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function sjactFormatter(value, row, index) {
    console.log("========sjactFormatter")
    console.log(row)
    var state = row.state;
    var id = row.id;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    if ($('#isAdmin').val() == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="setadmin(\'' + id + '\',\'' + row.name + '\',\'' + row.phone + '\')" >设置商户管理员</button>';
    if ($('#isAdmin').val() == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="setadminphone(\'' + id + '\')" >设置用户手机号</button>';

    return res;
}

var editsw = [];
/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#username').val(data.username)
    modal.find('#name').val(data.name)
    modal.find('#password').val(data.password)
    modal.find('#salt').val(data.salt)
    modal.find('#openid').val(data.openid)
    modal.find('#unionid').val(data.unionid)
    modal.find('#nickName').val(data.nickName)
    modal.find('#avatarPic').val(data.avatarPic)
    modal.find('#gender').val(data.gender)
    modal.find('#city').val(data.city)
    modal.find('#province').val(data.province)
    modal.find('#country').val(data.country)
    modal.find('#language').val(data.language)
    modal.find('#company').val(data.company)
    modal.find('#jobTitle').val(data.jobTitle)
    modal.find('#phone').val(data.phone)
    modal.find('#telphone').val(data.telphone)
    modal.find('#email').val(data.email)
    modal.find('#weixin').val(data.weixin)
    modal.find('#weibo').val(data.weibo)
    modal.find('#jifen').val(data.jifen)
    editsw["isMember"] == undefined ? editsw["isMember"] = new Switchery(document.querySelector('#isMember'), {color: "#1AB394"}) : ""
    if (data.isMember == 1) {
        setSwitchery(editsw["isMember"], true);
    } else {
        setSwitchery(editsw["isMember"], false);
    }
    modal.find('#memberLevel').val(data.memberLevel)
    modal.find('#discount').val(data.discount)
    editsw["isEcashCard"] == undefined ? editsw["isEcashCard"] = new Switchery(document.querySelector('#isEcashCard'), {color: "#1AB394"}) : ""
    if (data.isEcashCard == 1) {
        setSwitchery(editsw["isEcashCard"], true);
    } else {
        setSwitchery(editsw["isEcashCard"], false);
    }
    modal.find('#pid').val(data.pid)
    editsw["state"] == undefined ? editsw["state"] = new Switchery(document.querySelector('#state'), {color: "#1AB394"}) : ""
    if (data.state == 1) {
        setSwitchery(editsw["state"], true);
    } else {
        setSwitchery(editsw["state"], false);
    }
    modal.find('#originType').find("option[value='" + data['originType'] + "']").attr("selected", true);
    modal.find('#userType').find("option[value='" + data['userType'] + "']").attr("selected", true);
    modal.find('#apptype').find("option[value='" + data['apptype'] + "']").attr("selected", true);
    modal.find('#version').val(data.version)
    modal.find('#remark').val(data.remark)
    editsw["isRegist"] == undefined ? editsw["isRegist"] = new Switchery(document.querySelector('#isRegist'), {color: "#1AB394"}) : ""
    if (data.isRegist == 1) {
        setSwitchery(editsw["isRegist"], true);
    } else {
        setSwitchery(editsw["isRegist"], false);
    }
    modal.find('#sp').val(data.sp)
    modal.find('#mpid').val(data.mpid)
    modal.find('#subscribeTime').val(data.subscribeTime)
    modal.find('#modifier').val(data.modifier)

})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

function imgFormatter(value, row, index) {
    if (value) {
        return "<img src='" + value + "' width='25' height='25'>"
    } else {
        return "未上传图标";
    }
}

function tbfresh() {
    var p = {
        status: $('#qstatus').val(),
        search: $('#search').val(),
        ts: new Date().getTime()
    };
    console.log("======search_btn")
    console.log(p)
    $('#mytable').bootstrapTable('refresh', p);
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/user/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            // {
            //     title: '登陆账户',
            //     field: 'username'
            // },
            {
                title: '真实姓名',
                field: 'name'
            },
            {
                title: '昵称',
                field: 'nickName'
            },
            {
                title: '头像',
                field: 'avatarPic',
                formatter: "imgFormatter"
            },
            {
                title: '手机号',
                field: 'phone'
            },
            {
                title: '微信',
                field: 'weixin'
            },
            // {
            //     title: '当前积分',
            //     field: 'jifen'
            // },
            {
                title: '是否会员',
                field: 'isMember',
                formatter: "sfFormatter"
            },
            {
                title: '会员级别',
                field: 'memberLevel'
            },
            {
                title: '是否启用',
                field: 'state',
                formatter: "stateFormatter"
            },
            {
                title: '是否平台用户',
                field: 'isPlatform',
                formatter: "sfFormatter"
            },
            {
                title: '是否代理',
                field: 'isAgent',
                formatter: "sfFormatter"
            },
            {
                title: '是否商家',
                field: 'isMch',
                formatter: "sfFormatter"
            },
            {
                title: '来源方式',
                field: 'originType',
                formatter: "originTypeFormatter"
            },
            {
                title: '用户类型',
                field: 'userType',
                formatter: "userTypeFormatter"
            },
            {
                title: '注册时间',
                field: 'createtime'
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 260,
                formatter: sjactFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    // //请求服务数据时所传参数
    // function queryParams(params) {
    //     console.log(params)
    //     return params;
    // }
    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val()
            , status: $('#qstatus').val()
        }
        console.log("======queryParams")
        console.log(p)
        return p;
    }

    $('#search_btn').click(function () {
        tbfresh()
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    return true;
}